package com.enba.boot.i18n.resolver;

import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.LocaleResolver;

public class HeaderLocaleResolver implements LocaleResolver {
  @Override
  public Locale resolveLocale(HttpServletRequest request) {
    String language = request.getHeader("Accept-Language");
    Locale locale = Locale.getDefault();
    if (language != null && !language.isEmpty()) {
      String[] parts = language.split(",");
      String[] localeParts = parts[0].split("-");
      if (localeParts.length == 2) {
        locale = new Locale(localeParts[0], localeParts[1]);
      } else if (localeParts.length == 1) {
        locale = new Locale(localeParts[0]);
      }
    }
    return locale;
  }

  @Override
  public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    // 通常不需要实现此方法，因为我们是从请求头中解析语言信息
  }
}
